#define _CRT_SECURE_NO_WARNINGS 1
#include"Dlist.h"

DLN* CreatNewNode(DListDataType x)
{
	DLN* newnode = (DLN*)malloc(sizeof(DLN));
	if (newnode == NULL)
	{
		printf("malloc failed!\n");
		return NULL;
	}
	newnode->Data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

DLN* DLSTInit()
{
	DLN* newnode = CreatNewNode(0);
	newnode->next = newnode;
	newnode->prev = newnode;
	return newnode;
}

void DLSTPushBack(DLN* Phead, DListDataType x)
{
	assert(Phead);
	DLN* newnode = CreatNewNode(x);
	DLN* tail = Phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	Phead->prev = newnode;
	newnode->next = Phead;
}

void DLSTPrint(DLN* Phead)
{
	DLN* cur = Phead->next;
	while (cur != Phead)
	{
		printf("%d ", cur->Data);
		cur = cur->next;
	}
}

void DLSTPushFront(DLN* Phead, DListDataType x)
{
	assert(Phead);
	DLN* first = Phead->next;
	DLN* newnode = CreatNewNode(x);
	Phead->next = newnode;
	newnode->prev = Phead;
	newnode->next = first;
	first->prev = newnode;
}

void DLSTPopFront(DLN* Phead)
{
	assert(Phead);
	assert(Phead->next!=Phead);
	DLN* first = Phead->next;
	DLN* second = first->next;
	Phead->next = second;
	second->prev = Phead;
	free(first);
	first = NULL;
}

void DLSTPopBack(DLN* Phead)
{
	assert(Phead);
	assert(Phead->next != Phead);
	DLN* tail = Phead->prev;
	DLN* previous = tail->prev;
	free(tail);
	tail = NULL;
	previous->next = Phead;
	Phead->prev = previous;
}

DLN* DLSTDataFind(DLN* Phead, DListDataType x)
{
	assert(Phead);
	DLN* cur = Phead->next;
	while (cur != Phead)
	{
		if (cur->Data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void DLSTInsert(DLN* Phead, DLN* pos, DListDataType x)
{
	assert(Phead);
	DLN* newnode = CreatNewNode(x);
	DLN* prev = pos->prev;
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void DLSTErase(DLN* Phead, DLN* pos)
{
	assert(Phead);
	DLN* prev = pos->prev;
	DLN* next = pos->next;
	free(pos);
	pos = NULL;
	prev->next = next;
	next->prev = prev;
}